//伝統モンゴルIME　宝文首

//-----------控制
function loadIme(){
	//bind event;
	
	
	////////////////
	MC=new Object()
	MC.browser = 
    (navigator.appName.indexOf('Microsoft') != -1) ? 1 :
    (navigator.appName.indexOf('Netscape')  != -1) ? 2 :
    (navigator.appName.indexOf('Opera')     != -1) ? 3 : 4;
    if(MC.browser == 2 && navigator.userAgent.indexOf('Safari') != -1){ MC.browser = 5;}
    
    MC.vlamjilaltServerUrl = "../lib/xvlvn/vlamjilalt_ime_server.php";
	MC.serverUrl = "../lib/xvlvn/ime_server.php";
    //var sang = '';//
    MC.englishMode = false;//english or mongolian
    MC.vlamjilaltMode = true;//english or mongolian vlamjilaltModeFlag
    $("body").append('<div id="IMEoutput" class="ime-mongol"><div id="imeName"><input type="checkbox" name="vlamjilaltModeFlag" id="vlamjilaltModeFlag" style="display:none;"><p style="padding:3px;color:#FFF;text-align:center;"></p></div><div id="abiya"></div><ul id="svngvlt"></ul></div>');
    
    MC.nairag = $("#body");
    MC.nairagTagName = "input";
    MC.abiya = "";
	
	MC.out=$('#IMEoutput');
	MC.out_svngvlt = $('#IMEoutput').find('#svngvlt').css("background-color","#eaeaea");
	MC.out_abiya = $('#IMEoutput').find('#abiya').css({"background-color":"#eaeaea","padding":"3px"});
	MC.clear = function(){
		MC.abiya = '';
		$('#IMEoutput').find('#abiya').html('');
		$('#IMEoutput').find('#svngvlt').html('');
		
	}
	MC.insertToNairag = function(value){
		$("#"+MC.nairag).focus();
		$("#"+MC.nairag).insertAtCaret(value);
	}
	MC.ajaxRequest;
	MC.getServerUrl= function(){
		if(this.vlamjilaltMode){
			return this.vlamjilaltServerUrl;
		}else{
			return this.serverUrl;
		}
	};
	MC.out_svngvlt.find("li").live("click",function(){
			MC.insertToNairag($(this).find("div[name=charWord]").html());
			MC.clear();
			MC.nairag.focus();
	});
	
	$('[imode=mongol]')
	.live("focus",function(){
		MC.nairagTagName = $(this).get(0).tagName.toLowerCase(); 
		MC.nairag=$(this).attr("id"); 
	})	
	.live("keypress",imeKeypress)
	.live("keydown",imeKeydown)
	.live("keyup",imeKeyup);
	if(MC.vlamjilaltMode){
		$("#imeName").find("#vlamjilaltModeFlag").attr("checked","checked");
		$("#imeName").find("p").text("ᠪᠣᠷᠣ ᠪᠢᠷ");
		MC.out.css("background-color","#408040");
	}else{
		$("#imeName").find("#vlamjilaltModeFlag").removeAttr("checked");
		$("#imeName").find("p").text("ᠮᠡᠷᠭᠡᠨ ᠪᠢᠷ");
		MC.out.css("background-color","#8B1A1A");
	}
	$("#imeName").click(function(){
		if($(this).find("#vlamjilaltModeFlag").attr("checked")){
			$(this).find("#vlamjilaltModeFlag").removeAttr("checked");
			$(this).find("p").text("ᠮᠡᠷᠭᠡᠨ ᠪᠢᠷ");
			MC.out.css("background-color","#8B1A1A");
			MC.vlamjilaltMode=false;
		}else{
			$(this).find("#vlamjilaltModeFlag").attr("checked","checked");
			$(this).find("p").text("ᠪᠣᠷᠣ ᠪᠢᠷ");
			MC.out.css("background-color","#408040");
			MC.vlamjilaltMode=true;
		}
		sendKeyString(MC.abiya);
		$("#"+MC.nairag).focus();
		
	});
	MC.out_abiya.click(function(){
		$("#"+MC.nairag).focus();
	});

}
function sendKeyString(keys){
	if(MC.ajaxRequest){MC.ajaxRequest.abort();}
	MC.ajaxRequest= $.ajax({
		url:MC.getServerUrl(),//"../include/ime_server.php",
		success:function(result){
			$('#IMEoutput').find('#svngvlt').html('');
			$('#IMEoutput').find('#abiya').html(result.abiya);
			if(typeof(result.botool)!='undefined'){
				for(i=0;i<result.botool.length;i++){
					
					//MC.out_svngvlt.append("<li id='item"+(i+1)+"'><div name='WordIndex'>"+ (i+1) +".</div><div name='charWord'>"+advance(result.botool[i])+"</div></li>");
					$('#IMEoutput').find('#svngvlt').append("<li id='item"+(i+1)+"'><div name='WordIndex'>"+ (i+1) +".</div><div name='charWord'>"+advance(result.botool[i])+"</div></li>");
				}
			}
			if(typeof(result.word)!='undefined'){
				MC.out_svngvlt.append("<li id='item0'><div name='WordIndex'>0.</div><div name='charWord'>"+advance(result.word)+"</div></li>");
			}
			$('#IMEoutput').find('#svngvlt').find('li:first').addClass('selected');
		},
		complete:function(XHR, TS){
			//alert(TS);
		},
		error:function(XHR, MSG){
			//alert(XHR);
		},
		data:{k:keys},
		dataType:'json'
	});
}
function sendNewWord(word,listIndex){
	$.ajax({
		url:"../lib/xvlvn/push.php",
		success:function(){},
		data:{w:word,o:listIndex},
	});
}

function imeKeypress(e){ 

	//if(!e) e=window.event;
	var key = e.which ? e.which : e.keyCode;
	//alert(key);
	// pass keypress without processing it
	//if(passNextKeyPress) {
	//	return (true);
	//}

	// Gecko 虽不能于 OnKeyDown 取消键，但它却是在 OnKeyPress 之后才执行键的动作，故于 ssss;@- 取消键亦无所谓。
	// 但 Opera 在 OnKeyPress 之前已执行键的动作，故仍未能取消 Backspace 等键。  
	// 为什么不连IE也在此取消多一次？即在OnKeyDown取消，在OnKeyPress再取消。因会出现一个问题：快速输入文字时，第一个字会被取消。原因未知。
    //if (CancelKey) {
	//	CancelKey = false;
	//	return (false);
	//}

	//if (e.ctrlKey) { return (true); }

	// 为何不将A-Z的处理放在OnKeyDown ? 因无从知道Caps Lock的状况。
	//==A-Z
	
	if ( key>=65 && key<=90 ) {
		if (MC.englishMode==false && MC.abiya.length<40) {
		//alert('imeKeypress+'+key);
			MC.abiya += String.fromCharCode(key);
			sendKeyString(MC.abiya);
			return (false);
		}
	//==a-z	
	}else if (key>=97 && key<=122) {
		if (MC.englishMode==false && MC.abiya.length<40) {
			MC.abiya += String.fromCharCode(key);
			sendKeyString(MC.abiya);
			return (false);
		}
		
		//
		//return true;
	//0-9
	}else if(key>=48 && key<=57){
		if(MC.abiya!=''){
			listIndex = String.fromCharCode(key);
			if(key == 48 || key>53){//0 or >5
				sendNewWord($('li#item'+listIndex+' div[name=charWord]').html(),listIndex);
			}else if(key>48 && key<=53){
				if(MC.abiya.match('\'')!=null){
					sendNewWord($('li#item'+listIndex+' div[name=charWord]').html(),99);
				}
			}
			if($('li#item'+String.fromCharCode(key)).size()>0){
				MC.insertToNairag($('li#item'+String.fromCharCode(key)+' div[name=charWord]').html());
				MC.clear();
			}
			
			return false;
		}else{
			return true;
		}
	}else if(key==39){// '
		if (MC.abiya!='') {
			MC.abiya += "'";
			sendKeyString(MC.abiya);
			return (false);
		}else{
			return true;
		}
		
	}else if(false && key == 13){//return
		if(MC.abiya!=''){
			return false;
		}else{
			return true;
		}	
	}else if(false && key == 8){//packspace
		return false;
	}else if(key == 32){//space
		if(MC.abiya!=''){
			//liId=$('li.selected').attr('id').replace('item','');
			//if(liId==0 || liId>5){
			//	sendNewWord($('li.selected div[name=charWord]').html(),liId);
			//}else if(MC.abiya.match('\'')!=null){
			//	sendNewWord($('li.selected div[name=charWord]').html(),99);
			//}
			
			MC.insertToNairag($('li.selected div[name=charWord]').html());
			MC.clear();
			return false;
		}else{
			return true;
		}
	}else if(false && key == 38){//up
		if(MC.abiya!=''){
			var crrIndex = MC.out_svngvlt.find('li.selected').index();
			if(crrIndex-1>=0){
				var nextLi = MC.out_svngvlt.find('li').removeClass('selected').get(crrIndex-1);//.addClass('selected');
				$(nextLi).addClass('selected');
			}
			return false;
		}else{
			return true;
		}	
	}else if(false && key == 40){//down
		if(MC.abiya!=''){
			var crrIndex = MC.out_svngvlt.find('li.selected').index();
			if(crrIndex+1<MC.out_svngvlt.find('li').size()){
				var nextLi = MC.out_svngvlt.find('li').removeClass('selected').get(crrIndex+1);
				$(nextLi).addClass('selected');
			}
			return false;
		}else{
			return true;
		}	
	}else if(key == 44 || key == 46 || key == 60 || key == 62 || key == 124 || key == 125){
			if(MC.abiya!=''){
				liId=$('li.selected').attr('id').replace('item','');
				if(liId==0 || liId>5){
					sendNewWord($('li.selected div[name=charWord]').html(),liId);
				}else if(MC.abiya.match('\'')!=null){
					sendNewWord($('li.selected div[name=charWord]').html(),99);
				}
				
				MC.insertToNairag($('li.selected div[name=charWord]').html());
				MC.clear();	
			}
			if(key == 44){
				MC.insertToNairag("᠂ ");
			}else if(key == 46){
				MC.insertToNairag("᠃ ");
			}else if(key == 60){
				MC.insertToNairag("《");
			}else if (key == 62){
				MC.insertToNairag("》");
			}else if(key == 124){
				MC.insertToNairag("〉");
			}else if (key == 125){
				MC.insertToNairag("〈");
			}
			
			return false;
	}else{
		if(MC.abiya!=''){
				liId=$('li.selected').attr('id').replace('item','');
				if(liId==0 || liId>5){
					sendNewWord($('li.selected div[name=charWord]').html(),liId);
				}else if(MC.abiya.match('\'')!=null){
					sendNewWord($('li.selected div[name=charWord]').html(),99);
				}
				MC.insertToNairag($('li.selected div[name=charWord]').html());
				MC.clear();	
			}
		return true;
	}
}
function imeKeydown(event){
	var key = event.keyCode;
	switch (key){
		case 16://shift
			//MC.englishMode = !MC.englishMode;
			//alert(MC.englishMode);
			return true;
		case 8://==Backspace
    		if(MC.abiya!=''){
				MC.abiya = MC.abiya.substr(0,MC.abiya.length-1);
				if(MC.abiya.length>0){
					sendKeyString(MC.abiya);
				}else{
					if(!MC.ajaxRequest){
						MC.ajaxRequest.abort();
					}
					MC.clear();
				}
				return (false);
			}else{
				return (true);
			}	
	  	case 9://==Tab
		    return (false); 
		case 27://==Esc
			return (false); //Esc会把全部文字删除，故禁止Esc键。
		  //向前翻页
		case 109: //firfox keycode '-'
		       if(browser != 2) break;
		case 189: //ie keycode '-'
		       if(browser != 1 && key != 109) break;
		  //==PageUp
		case 33:
		case 57383: // Opera 7.11
		    break;//return(true);
		//向后翻页
		case 61: //firfox keycode '-'
			if(browser != 2) break;
		case 187: //ie keycode '-'
			if(browser != 1 && key != 61) break;
		//==PageDown
		case 34:
		case 57384: // Opera 7.11
			break;
			//return(true);
		case 32: //==Space
			return(true);
		case 13: //==Enter
			if(MC.abiya!=''){
				liId=$('li.selected').attr('id').replace('item','');
				MC.insertToNairag(MC.abiya);
				MC.clear();
				return false;
			}else{
				return true;
			}
			
			
				
		case 113://==F2
			return (false);
		case 123://==F12
		case 57356: // Opera 7.11
			return (false);
		case 17://==Ctrl
		case 57402: // Opera 7.11
			CtrlDown=true;
			break;
		case 36: // home
		case 35: // end
		case 37: // left
		case 38: // up
			if(MC.abiya!=''){
				var crrIndex = MC.out_svngvlt.find('li.selected').index();
				if(crrIndex-1>=0){
					var nextLi = MC.out_svngvlt.find('li').removeClass('selected').get(crrIndex-1);//.addClass('selected');
					$(nextLi).addClass('selected');
				}
				return false;
			}else{
				return true;
			}
		case 39: // right
		case 40: // down
			if(MC.abiya!=''){
				var crrIndex = MC.out_svngvlt.find('li.selected').index();
				if(crrIndex+1<MC.out_svngvlt.find('li').size()){
					var nextLi = MC.out_svngvlt.find('li').removeClass('selected').get(crrIndex+1);
					$(nextLi).addClass('selected');
				}
				return false;
			}else{
				return true;
			}
		case 45: // insert
		case 46: // del
		case 91: // windows key
		case 112: // F1
		//case 113: // F2
		case 114: // F3
		case 115: // F4
		case 116: // F5
		case 117: // F6
		case 118: // F7
		case 119: // F8
		case 120: // F9
		case 121: // F10
		case 122: // F11
		//case 123: // F12
		// let these keys pass through unprocessed in the next keypress events
	
		return (false);
	}
	return true;
}

function imeKeyup(event){

}
//光标处写入内容控件
(function($){
	$.fn.extend({
		insertAtCaret: function(myValue){
			var $t=$(this)[0];
			$(this).focus();
			if (document.selection) {
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
			}else if ($t.selectionStart || $t.selectionStart == '0') {
				var startPos = $t.selectionStart;
				var endPos = $t.selectionEnd;
				var scrollTop = $t.scrollTop;
				$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
				this.focus();
				$t.selectionStart = startPos + myValue.length;
				$t.selectionEnd = startPos + myValue.length;
				$t.scrollTop = scrollTop;
			}else if(window.getSelection){
				var scrollTop = $t.scrollTop;
				var rng = window.getSelection().getRangeAt(0);//.cloneRange();  
				rng.deleteContents();
	            var txt = document.createTextNode(myValue);
	            rng.insertNode(txt);
	            
	            
	            rng = rng.cloneRange();  
                rng.setStartAfter(txt);
                //rng.setEndAfter(txt);   
                rng.collapse(false);  
                window.getSelection().removeAllRanges();  
                window.getSelection().addRange(rng);  
				
	            //this.focus();
			}else{
				this.innerHTML = myValue;
				this.focus();
			}
		}
	}) 
})(jQuery);

////////////样式表
var css = '';
css+=".ime-mongol{";
css+="'Mongolian White', Serif;";
css+="-moz-writing-mode: vertical-lr;";
css+="writing-mode: vertical-lr;";
css+="-webkit-writing-mode: vertical-lr;";
css+="-o-writing-mode: vertical-lr;";
css+="-ms-writing-mode: tb-lr;";
css+="writing-mode: tb-lr;";

css+="position: absolute;";
css+="bottom: 0;";
css+="right:0;";
css+="z-index:100;";
css+="}";

css+="#IMEoutput li{";
css+="min-height:100px;";
css+="width:40px;";
css+="line-height:40px;";
css+="}";

css+="#IMEoutput li.selected{";
css+="background:#6666FF;";
css+="color:#FFF;";
css+="border-radius:3px;";
css+="}";

css+="#IMEoutput li div[name=WordIndex]{";
css+="float:left;";
css+="}";

css+="#IMEoutput li div[name=charWord]{";
css+="margin-top:20px;";
css+="}";
passwordStyle=document.createElement('style');
if (passwordStyle.styleSheet){
    passwordStyle.styleSheet.cssText=css;
}else{ 
    passwordStyle.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(passwordStyle);